﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace Jmit.Common
{
    class HttpUtils
    {
        public static string HttpRequestFromPost(string maiurl, string paramurl)
        {
            string strHtmlContent = "";
            HttpWebRequest request;
            try
            {
                //Encoding encoding = Encoding.GetEncoding("GB2312");
                //Encoding encoding = Encoding.GetEncoding("utf-8");
                Encoding encoding = Encoding.GetEncoding("GBK");
                //声明一个HttpWebRequest请求
                request = (HttpWebRequest)WebRequest.Create(maiurl);
                request.Method = "POST";
                request.Proxy = null;             //设置代理为NULL，解决第一次连接超时问题
                request.ContentType = "application/x-www-form-urlencoded;";
                request.Timeout = 10 * 1000; //请求超时前等待的毫秒数。 默认值是 100,000 毫秒（100 秒）。
                //request.ContentType = "application/json";
                //request.Headers.Add("Authorization", "Bearer ");

                //charset=gb2312
                request.AllowAutoRedirect = true;

                //byte[] Postbyte = Encoding.ASCII.GetBytes(paramurl);
                byte[] Postbyte = Encoding.UTF8.GetBytes(paramurl);
                request.ContentLength = Postbyte.Length;
                Stream newStream = request.GetRequestStream();
                newStream.Write(Postbyte, 0, Postbyte.Length);//把参数用流对象写入request对象中   
                newStream.Close();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();//获得服务器响应对象  
                Stream resStream = response.GetResponseStream();//转成流对象   
                StreamReader sr = new StreamReader(resStream, encoding);
                strHtmlContent = sr.ReadToEnd();
                response.Close();
            }
            catch (Exception ex)
            {

            }
            finally
            {
                request = null;
            }
            if (strHtmlContent == null)
                strHtmlContent = "";
            return strHtmlContent;
        }
    }
}
